<template>
    <div class="sales-product-container">
        <h2>发票登记</h2>
        <br />

        <!-- 查询表单 -->
        <el-form :model="searchForm" label-width="auto" class="sales-product-form">
            <div class="form-row">
                <el-form-item label="有效日期：" prop="dateRange">
                    <el-date-picker v-model="dateRange" type="daterange" range-separator="~" start-placeholder="开始日期"
                        end-placeholder="结束日期" style="width: 390px;" @change="handleDateChange"
                        value-format="YYYY-MM-DD" />
                </el-form-item>

                <el-form-item label="单据编号：" prop="salesSlipCode">
                    <el-input v-model="searchForm.salesSlipCode" placeholder="单号" style="width: 200px;" />
                </el-form-item>


                <el-form-item label="客户：">
                    <el-input v-model="searchForm.customerCode" placeholder="点击选择客户" @click="openCustomerDialog"
                        readonly style="width: 200px;" />
                    <CustomerDialog v-model="customerDialogVisible" @confirm="handleSelectCustomer" />
                </el-form-item>


                <el-form-item label="销售员：" prop="workNumber">
                    <el-select v-model="searchForm.workNumber" placeholder="请选择" clearable style="width: 160px;">
                        <el-option v-for="salesPerson in salesPersonList" :key="salesPerson.id"
                            :label="salesPerson.name" :value="salesPerson.workNumber" />
                    </el-select>
                </el-form-item>

                <el-form-item label="订单类型:">
                    <el-select v-model="searchForm.isReturn" placeholder="请选择" style="width: 200px;">
                        <el-option label="销售单" :value="0" />
                        <el-option label="销售退货单" :value="1" />
                    </el-select>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="handleSearch">查询</el-button>
                </el-form-item>
            </div>
        </el-form>

        <!-- 操作按钮：导出、开票记录等 -->
        <div class="form-actions">
            <el-button type="primary" @click="handleInvoiceRegister">发票登记</el-button>
            <el-button @click="handleOpenRecord">开票记录</el-button>
            <el-button @click="handleExport">导出</el-button>
            <el-button>打印</el-button>
        </div>

        <!-- 数据表格 -->
        <el-table :data="tableData" border style="width: 100%" :summary-method="getSummary" show-summary
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="date" label="单据日期" width="160" />
            <el-table-column label="单据编号" width="170">
                <template #default="scope">
                    {{ scope.row.isReturn === 1 ? scope.row.returnCode : scope.row.code }}
                </template>
            </el-table-column>
            <!-- <el-table-column prop="salesSlip_code" label="源销货订单号" width="160" /> -->
            <el-table-column prop="customerName" label="客户" width="180" />
            <el-table-column prop="workName" label="销售人员" width="120" />
            <el-table-column prop="itemCount" label="数量" width="100" />
            <el-table-column prop="slipPrice" label="金额" width="120" />
            <el-table-column prop="written_off_amount" label="已收款金额" width="120" />
            <!-- <el-table-column prop="hxStatus" label="收款状态" width="120" /> -->
            <el-table-column prop="invoicedAmount" label="已开票金额" width="130" />
            <el-table-column prop="notAmount" label="未开票金额" width="130" />
            <el-table-column prop="taxAmount" label="税额" width="120" />
            <el-table-column prop="currentInvoiceAmount" label="*本次开票金额" width="140">
                <template #default="scope">
                    <el-input v-model="scope.row.currentInvoiceAmount" @input="handleAmountChange(scope.row)"
                        style="width: 100px;" />
                </template>
            </el-table-column>
            <el-table-column prop="remarks" label="整单备注" min-width="180" />
        </el-table>

        <!-- 分页 -->
        <div style="float: right; padding-top: 20px;">
            <el-pagination background layout="prev, pager, next,jumper" :total="pageInfo.total"
                :page-size="pageInfo.pageSize" :current-page="pageInfo.pageNum" @current-change="changePage" />
        </div>
        <div style="clear: both;"></div>
    </div>

    <!-- 底部开票信息输入区 -->
    <div class="footer-form">
        <el-form :inline="true" label-width="auto" style="margin-top: 16px;">
            <div class="form-row" style="gap: 16px; align-items: center;">
                <el-form-item label="开票日期：" required>
                    <el-date-picker v-model="invoiceForm.invoiceDate" type="date" placeholder="选择日期"
                        value-format="YYYY-MM-DD" style="width: 200px;" />
                </el-form-item>

                <el-form-item label="发票号：" required>
                    <el-input v-model="invoiceForm.invoiceNumber" placeholder="请输入发票号" style="width: 200px;"
                        @blur="isInvNumber" />
                </el-form-item>

                <el-form-item label="发票金额：">
                    <el-input v-model="invoiceForm.invoiceAmount" placeholder="0.00" style="width: 200px;" disabled />
                </el-form-item>


                <el-form-item label="开票备注：">
                    <el-input v-model="invoiceForm.remarks" placeholder="请输入备注" style="width: 200px;" />
                </el-form-item>
            </div>
        </el-form>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import CustomerDialog from '@/util/CustomerDialog.vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'


// 分页信息
const pageInfo = reactive({
    List: [],
    total: 0,
    pageSize: 10,
    pageNum: 1,
    pages: 0,
})

// 查询表单数据
const searchForm = reactive({
    start_date: '',
    end_date: '',
    salesSlipCode: '',
    customerCode: '',
    workNumber: '',
    auditStatus: 2,
    isReturn: 0,
})

// 表格数据
const tableData = ref([
])

// 开票表单
const invoiceForm = reactive({
    customerCode: '',
    customerName: '',
    invoiceDate: new Date(),
    invoiceNumber: '',
    invoiceAmount: 0,
    invoiceTitle: '',
    remarks: '',
    customer: '',
    salesPerson: '',

})

const selectedRows = ref([])

// 表格选择
const handleSelectionChange = (selection) => {
    selectedRows.value = selection
    calculateTotalInvoiceAmount()
}

const dateRange = ref([])
// 日期
const handleDateChange = (val) => {
    if (val && val.length === 2) {
        searchForm.start_date = val[0]
        searchForm.end_date = val[1]
    } else {
        searchForm.start_date = ''
        searchForm.end_date = ''
    }
}

// 计算
const handleAmountChange = (row) => {
    const inputValue = row.currentInvoiceAmount
    const regex = /^\d+$/

    if (!regex.test(inputValue)) {
        ElMessage.warning('本次开票金额必须为正整数')
        row.currentInvoiceAmount = ''
        return
    }

    const numValue = parseInt(inputValue)

    if (numValue > row.notAmount) {
        ElMessage.warning('本次开票金额不能超过未开票金额')
        row.currentInvoiceAmount = row.notAmount
    }

    calculateTotalInvoiceAmount()
}

// 计算选中行的发票总金额
const calculateTotalInvoiceAmount = () => {
    const total = selectedRows.value.reduce((sum, item) => {
        const amount = parseFloat(item.currentInvoiceAmount) || 0
        return sum + amount
    }, 0)
    invoiceForm.invoiceAmount = parseFloat(total).toFixed(2)
}

// 销售员列表
const salesPersonList = ref([
])
// 查询
const handleSearch = async () => {


    const response = await axios.get('/api/sales/selectSlipList', {
        params: {
            pageNum: pageInfo.pageNum,
            pageSize: pageInfo.pageSize,
            customerCode: searchForm.customerCode,
            end_date: searchForm.end_date,
            start_date: searchForm.start_date,
            workNumber: searchForm.workNumber,
            isReturn: searchForm.isReturn,
            auditStatus: searchForm.auditStatus,
            isInv: 1,
            ...(searchForm.isReturn == 1
                ? { returnCode: searchForm.salesSlipCode }
                : { code: searchForm.salesSlipCode })
        }

    })

    if (response.data.code == 200) {
        console.log('查询结果：', response.data)
        tableData.value = response.data.selectSlipList.list
        pageInfo.total = response.data.selectSlipList.total
        pageInfo.pages = response.data.selectSlipList.pages
    } else {
        ElMessage.error(response.data.msg)
        console.error('查询失败：', response.data.message)
    }

}

//销售员
const selectStaff = async () => {
    const response = await axios.get('/api/sales/selectStaff')
    if (response.data.code == 5200) {
        console.log('12', response.data)
        salesPersonList.value = response.data.saleStaffList
    } else {
        ElMessage.error(response.data.msg)
        console.error('获取销售员列表失败：', response.data.message)
    }
}


// 客户对话框启用
const customerDialogVisible = ref(false)
/**
 * 打开客户选择弹窗
 */

const openCustomerDialog = () => {
    customerDialogVisible.value = true
}

// 客户选择
const handleSelectCustomer = (customers) => {
    console.log('已选择客户:', customers)
    if (customers && customers.length > 0) {
        const customer = customers[0]
        searchForm.customerCode = customer.code
        searchForm.customerName = customer.name
    }
    customerDialogVisible.value = false
}

// 分页切换
const changePage = (pageNum) => {
    pageInfo.pageNum = pageNum
    handleSearch()

}

const isInvNumber = async () => {
    const response = await axios.get('/api/sales/checkInvNumber', {
        params: {
            invoiceNumber: invoiceForm.invoiceNumber.trim()
        }
    })

    if (response.data.code == 200) {
        return true
    } else {
        ElMessage.warning('发票号已存在，请重新输入')
        return false
    }
}

// 发票登记
const handleInvoiceRegister = async () => {

    const result = await isInvNumber()
    if (!result) {
        return
    }

    if (selectedRows.value.length === 0) {
        ElMessage.warning('请至少选择一条销售单进行开票')
        return
    }

    if (!invoiceForm.invoiceDate) {
        ElMessage.warning('请选择开票日期')
        return
    }
    if (!invoiceForm.invoiceNumber?.trim()) {
        ElMessage.warning('请输入发票号')
        return
    }

    //客户
    const firstCustomer = selectedRows.value[0].customer_code
    const allSameCustomer = selectedRows.value.every(row => row.customer_code === firstCustomer)
    if (!allSameCustomer) {
        ElMessage.warning('所选销售单必须属于同一客户才能合并开票')
        return
    }

    // 校验每行的本次开票金额
    for (const row of selectedRows.value) {
        const amount = parseFloat(row.currentInvoiceAmount)
        if (!amount || isNaN(amount) || amount <= 0) {
            ElMessage.warning(`单据 ${row.isReturn ? row.returnCode : row.code} 的本次开票金额无效`)
            return
        }
        if (amount > row.notAmount) {
            ElMessage.warning(`单据 ${row.isReturn ? row.returnCode : row.code} 的本次开票金额不能超过未开票金额`)
            return
        }
    }

    try {
        const invoiceRecords = selectedRows.value.map((row) => ({
            slipId: row.id,
            date: invoiceForm.invoiceDate,
            invoiceNumber: invoiceForm.invoiceNumber.trim(),
            currentInvoiceAmount: row.currentInvoiceAmount,
            salesSlipCode: row.isReturn ? row.returnCode : row.code,
            isReturn: row.isReturn,
            slipDate: row.date,
            customerCode: row.customer_code,
            customerName: row.customerName,
            workNumber: row.workNumber,
            workName: row.workName,
            salesAmount: row.salesAmount,
            taxAmount: row.taxAmount,
            slipPrice: row.slipPrice,
            remarks: invoiceForm.remarks,
            itemCount: row.itemCount || 0,
            status: 1,
        }))

        console.log('发送的发票记录:', invoiceRecords)

        const response = await axios.post('/api/sales/addInv', invoiceRecords, {
            headers: {
                'Content-Type': 'application/json'
            }
        })


        if (response.data.code == 200) {
            ElMessage.success('发票登记成功！')

            invoiceForm.invoiceDate = ''
            invoiceForm.invoiceNumber = ''
            invoiceForm.remarks = ''
            invoiceForm.invoiceAmount = '0.00'

            handleSearch()
        } else {
            ElMessage.error(response.data.msg || '发票登记失败')
        }
    } catch (error) {
        console.error('请求详细错误:', error.response?.data || error)
        if (error.response?.data) {
            ElMessage.error('请求失败: ' + JSON.stringify(error.response.data))
        } else {
            ElMessage.error('请求失败: ' + error.message)
        }
    }

}

// 开票记录
const handleOpenRecord = () => {
    alert('查看开票记录')
}

// 导出
const handleExport = () => {
    alert('导出数据')
}

// 合计行
const getSummary = (param) => {
    const { columns, data } = param
    const sums = []
    columns.forEach((column, index) => {
        if (index === 0) {
            sums[index] = '合计'
            return
        }
        const values = data.map(item => Number(item[column.property]))
        if (!values.every(val => !isNaN(val))) {
            sums[index] = ''
            return
        }
        const total = values.reduce((prev, curr) => prev + curr, 0)
        sums[index] = total.toFixed(2)
    })
    return sums
}

onMounted(() => {
    handleSearch()
    selectStaff()
})
</script>

<style scoped>
.sales-product-container {
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
}

.sales-product-form {
    max-width: 1400px;
}

.form-row {
    display: flex;
    gap: 20px;
    flex-wrap: wrap;
    align-items: center;
}


.form-actions {
    margin: 16px 0;
    float: right;
    gap: 12px;
    display: flex;
}

/* 表单项样式 */
.el-form-item__label {
    font-weight: bold;
    color: #333;
}

.el-form-item__content {
    display: flex;
    align-items: center;
}

.el-input__inner,
.el-select .el-input__inner {
    border-radius: 4px;
    border: 1px solid #dcdfe6;
}

.el-input__inner:focus,
.el-select .el-input__inner:focus {
    border-color: #409eff;
    outline: none;
}

/* 底部开票信息区域 */
.footer-form {
    padding: 16px 20px;
    background-color: #f9f9f9;
    border: 1px solid #eee;
    border-radius: 4px;
    margin-top: 20px;
}

/* 响应式 */
@media (max-width: 1000px) {
    .form-row {
        flex-direction: column;
    }

    .form-row .el-form-item {
        min-width: 100%;
    }

    .form-actions {
        float: none;
        justify-content: flex-start;
        margin-top: 20px;
    }
}
</style>